package com.doeis.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.List;

import com.doeis.minaserver.dao.User;
import com.doeis.minaserver.dao.UserDao;
import com.doeis.minaserver.packet.NettyMessageDecoder;
import com.doeis.minaserver.packet.NettyMessageEncoder;
import com.doeis.uwork.entity.ItemNotes;
import com.google.inject.Guice;
import com.google.inject.Injector;
  
/**  
 * mina客户端  
 * @author aniyo   
 * blog:http://aniyo.iteye.com
 */  
public class MinaClient2 {   
  
        EventLoopGroup group = new NioEventLoopGroup();

        public void connect(final int port, final String host, 
        		final String login,final String pwd,
        		final String userid,final String noteid) throws Exception {
    	// 配置客户端NIO线程组

	    	try {
	    	    Bootstrap b = new Bootstrap();
	    	    b.group(group).channel(NioSocketChannel.class)
	    		    .option(ChannelOption.TCP_NODELAY, true)
	    		    .handler(new ChannelInitializer<SocketChannel>() {
							@Override
							protected void initChannel(SocketChannel socketChannel) throws Exception {
								socketChannel.pipeline().addLast(new NettyMessageDecoder());
								socketChannel.pipeline().addLast(new NettyMessageEncoder());
								socketChannel.pipeline().addLast(new NettyClientChannelHandlerAdapter3(login, pwd, userid, noteid ));
							}
								
						});
	    	    // 发起异步连接操作
	    	    ChannelFuture future = b.connect( new InetSocketAddress(host, port)).sync();
	    	    future.channel().closeFuture();
	    	} finally {

    		}
        }

        /**
         * @param args
         * @throws Exception
         */
        public static void main(String[] args) throws Exception {
        	MinaClient2 minaClient = new MinaClient2() ;
        	Injector injector = Guice.createInjector();
        	UserDao userDao = injector.getInstance(UserDao.class);
        	List<ItemNotes> listItemNote = userDao.query(ItemNotes.class, "select * from item_notes where creater_at >= '2016-05-19 17:00:39' group by user_id order by creater_at desc  ");
        	for(ItemNotes note : listItemNote){
        		User user =  userDao.findUserByid(note.getUser_id(), false);
        		minaClient.connect(9999, "192.168.1.113", user.getLogin(), "123", user.getId(), note.getId());
        	}
        	
        }

}